package com.github.postsanf.yinian.activity;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.LocalStickyImportPregressGridAdapter;
import com.github.postsanf.yinian.bean.ShowBackup;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.service.ImportService;
import com.github.postsanf.yinian.utils.DisplayUtil;
import com.github.postsanf.yinian.utils.SnackBarUtils;
import com.github.postsanf.yinian.utils.SpUtils;
import com.github.postsanf.yinian.utils.YNNativeComparator;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class ImporProgressActivity extends BaseActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private ProgressBar import_progress;
    private ViewPager vp_import_progress;
    private TextView import_percent;
    private RelativeLayout rl_import_message;
    private TextView import_total_pic;
    private int totalPic;
    private int picNumber;
    private GridView import_grid_view;
    private List<YNNativeImage> mNativeImageList = new ArrayList<>();
    private Map<String, Integer> sectionMap = new HashMap<>();
    private LocalStickyImportPregressGridAdapter mAdapter;
    private static int section = 1;
    private String date;
    private LinearLayout ll_import_toolbar;
    private ImageView iv_dustbin;
    private ImageView iv_share_import;
    private ImageView iv_import_download;
    private boolean isSelected = false;
    private ProgressDialog mProgressDialog;
    private DownloadManager manager;
    private ImageButton fab_publish_status;
    private TextView tv_cancle;
    private TextView tv_seceted;
    private boolean first = true;
    private boolean start = false;
    private ImageView iv_voice_progress;
    private RelativeLayout.LayoutParams layoutParams;
    private int width;
    private Map<String, List<YNNativeImage>> sortPic = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_impor_progress);
        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        registerReceiver();
        initView();
//        showBackup();
        //获取下载服务
//        Log.d("yuhao", "onCreate: ");
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                SharedPreferences sp = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
//                totalPic = sp.getInt("totalPic", 0);
//                picNumber = sp.getInt("picNumber", 0);
//                if (totalPic == 0) {
//                    fab_publish_status.setVisibility(View.VISIBLE);
//                } else {
//                    fab_publish_status.setVisibility(View.GONE);
//                }
//                if (SelectedImg.mSelectedImage.size() == 0) {
//                    if (picNumber == 0) {
//                        rl_import_message.setVisibility(View.GONE);
//                        fab_publish_status.setVisibility(View.VISIBLE);
//                    } else if(picNumber!=0&&network){
//                        toStartService();
//                        int progress = sp.getInt("progress", 0);
//                        import_progress.setProgress(progress);
//                        import_percent.setText(progress + "%");
//                        fab_publish_status.setVisibility(View.GONE);
//                        Log.d("yuhao", "fab_publish_status");
//                    }
//                }
//                import_total_pic.setText(totalPic + "张");
//            }
//        },50);
    }

    boolean network = false;

    private void toStartService() {
        Intent mIntent = new Intent(this, ImportService.class);
        mIntent.setAction(ACTIONs.actionPublishPhoto);
        mIntent.putExtra(ACTIONs.picNumber, totalPic);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        startService(mIntent);
    }

    // 注册广播接收器
    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTIONs.actionUpdateProgress);
        filter.addAction(ACTIONs.actionDeleteList);
        filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        filter.addAction(ACTIONs.network);
        registerReceiver(uploadImgReceiver, filter);
    }

    // 进度更新广播接收器
    private BroadcastReceiver uploadImgReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case ACTIONs.actionUpdateProgress:
                    int upProgress = intent.getIntExtra(ACTIONs.aUpProgress, 0);
                    handleResult(upProgress);
                    break;
                case ACTIONs.actionDeleteList:
                    SelectedImg.dateUrl.clear();
                    SelectedImg.mSelectedImage.clear();
                    SelectedImg.selectedNetPic.clear();
                    rl_import_message.setVisibility(View.GONE);
                    fab_publish_status.setVisibility(View.VISIBLE);
                    showBackup();
                    break;
                case DownloadManager.ACTION_DOWNLOAD_COMPLETE:
                    SnackBarUtils.makeShort(mToolbar, "保存成功！").success();
                    mAdapter.notifyDataSetChanged();
                    SelectedImg.selectedNetPic.clear();
                    break;
                case ACTIONs.network:
                    Log.i("xjs", "imporprogressac+necwork===>");
                    //经过Splash界面表示程序退出后从新进入
                    SharedPreferences spImport = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = spImport.edit();
                    edit.putBoolean("exit", true);
                    edit.commit();
                    ConnectivityManager connectivityManager = (ConnectivityManager)
                            getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                    if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        network = true;
                        SpUtils.put(ImporProgressActivity.this, "wifi", network);
                        if (!start) {
                            toGetProgress();
                            start = true;
                        }
                    } else {
                        network = false;
                        SpUtils.put(ImporProgressActivity.this, "wifi", network);
                        showToast("请在WIFI环境下上传图片");
                    }
                    break;
            }
        }
    };

    private void toGetProgress() {
        SharedPreferences sp = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
        totalPic = sp.getInt("totalPic", 0);
        picNumber = sp.getInt("picNumber", 0);
        if (first && network) {
            first = false;
            if (totalPic == 0) {
                rl_import_message.setVisibility(View.GONE);
                fab_publish_status.setVisibility(View.VISIBLE);
            } else {
                rl_import_message.setVisibility(View.VISIBLE);
                fab_publish_status.setVisibility(View.GONE);
                toStartService();
                int progress = sp.getInt("progress", 0);
                import_progress.setProgress(progress);
                import_percent.setText(progress + "%");
                layoutParams.leftMargin = (int) (progress * width * 0.01f);
                iv_voice_progress.setLayoutParams(layoutParams);
                fab_publish_status.setVisibility(View.GONE);
            }
        }
        import_total_pic.setText(totalPic + "张");
        //离开WIFI环境的情况下重新返回WIFI环境下会连续收到两次广播启动两次服务因此延时将first=true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                first = true;
                start = false;
            }
        }, 20);
    }

    // 同步更新上传进度条
    private void handleResult(int upprogress) {
        if (100 <= upprogress) {
            layoutParams.leftMargin = (int) (upprogress * width * 0.01f);
            iv_voice_progress.setLayoutParams(layoutParams);
            import_progress.setProgress(100);
            import_percent.setText("100%");
        } else {
            layoutParams.leftMargin = (int) ((0.01f * upprogress) * width);
            iv_voice_progress.setLayoutParams(layoutParams);
            import_progress.setProgress(upprogress);
            import_percent.setText(upprogress + "%");
        }
    }

    private void initView() {
        mToolbar = ((Toolbar) findViewById(R.id.import_progress_toolbar));
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        int windowWidth = DisplayUtil.getWindowWidth(ImporProgressActivity.this);
        width = windowWidth - UIHelper.dip2px(this, 30);
        iv_voice_progress = ((ImageView) findViewById(R.id.iv_voice_progress));
        layoutParams = new RelativeLayout.LayoutParams(UIHelper.dip2px(this, 25), UIHelper.dip2px(this, 15));
        import_progress = ((ProgressBar) findViewById(R.id.import_progress));
        vp_import_progress = ((ViewPager) findViewById(R.id.vp_import_progress));
        import_percent = ((TextView) findViewById(R.id.import_percent));
        rl_import_message = ((RelativeLayout) findViewById(R.id.rl_import_message));
        import_total_pic = ((TextView) findViewById(R.id.import_total_pic));
        ll_import_toolbar = ((LinearLayout) findViewById(R.id.ll_import_toolbar));
        iv_dustbin = ((ImageView) findViewById(R.id.iv_dustbin));
        iv_share_import = ((ImageView) findViewById(R.id.iv_share_import));
        iv_import_download = ((ImageView) findViewById(R.id.iv_import_download));
        fab_publish_status = (ImageButton) findViewById(R.id.fab_publish_status);
        tv_cancle = ((TextView) findViewById(R.id.tv_cancle));
        tv_seceted = ((TextView) findViewById(R.id.tv_seceted));
        tv_cancle.setOnClickListener(this);
        tv_seceted.setOnClickListener(this);
        fab_publish_status.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent2Activity(LocalAlbumImportActivity.class);
                start = false;
            }
        });
        iv_dustbin.setOnClickListener(this);
        iv_share_import.setOnClickListener(this);
        iv_import_download.setOnClickListener(this);
        import_grid_view = ((GridView) findViewById(R.id.import_grid_view));
        mAdapter = new LocalStickyImportPregressGridAdapter(this, mNativeImageList, false);
        import_grid_view.setAdapter(mAdapter);
        data2View();
        boolean bb = getIntent().getBooleanExtra(ACTIONs.IstoSetWifi, false);
        if (bb) {
            ToSetWifiDialog();
        }
        import_grid_view.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //第一个条目加上屏幕内可见条目等于总条目说明已经到底了，加载下一页
                if (totalItemCount > 18 && firstVisibleItem + visibleItemCount == totalItemCount) {
                    //是否正在刷新
                    if (isLoading) {
//                        showToast("正在刷新中...");
                        return;
                    }
                    loadMore(firstVisibleItem, "loading");
                    isLoading = true;
                }
//                Log.d("yuhao", "firstVisibleItem=" + firstVisibleItem);
//                String time = mNativeImageList.get(firstVisibleItem).getTime();
//                int backupPhotoID = mNativeImageList.get(firstVisibleItem).getBackupPhotoID();
//                List<YNNativeImage> ynNativeImages = sortPic.get(time);
//                for (int i = 0; i < ynNativeImages.size(); i++) {
//                    if (ynNativeImages.get(i).getBackupPhotoID() == backupPhotoID) {
//                        if (i != 0) {
//                            Log.d("yuhao", "i=" + i);
//                            sendBroadcast(new Intent(ACTIONs.invisibale).putExtra("time", time));
//                        } else {
////                            sendBroadcast(new Intent(ACTIONs.visibale).putExtra("time",time));
//                        }
//                        return;
//                    }
//                }
            }
        });
    }

    private boolean isLoading = false;

    private void loadMore(final int totalItemCount, String initialize) {
        showToast("正在为您加载下一页...");
        String urlsto = getString(R.string.BASE_URL) + getString(R.string.showBackupPhotos);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, application.getCurID() + "");
        if (TextUtils.equals(initialize, "initialize")) {
            mParam.put(CommonConstants.SIGN, "initialize");
        } else {
            mParam.put(CommonConstants.DATE, date);
            mParam.put(CommonConstants.SIGN, "loading");
        }
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        ShowBackup showBackup = gson.fromJson(s, ShowBackup.class);
                        if (TextUtils.equals(showBackup.getMsg(), "success")) {
//                            Log.d("yuhao", "mProgressDialog");
                            List<ShowBackup.DataBean> data = showBackup.getData();
                            if (data.size() == 0) {
                                showToast("已经到底啦...");
                                return;
                            }
                            String backupEventIDStr = null;
                            for (int i = 0; i < data.size(); i++) {
                                String backupDate = data.get(i).getBackupDate();
                                int backupEventID = data.get(i).getBackupEventID();
                                List<ShowBackup.DataBean.BackupPhotoBean> backupPhoto = data.get(i).getBackupPhoto();
                                if (backupPhoto.size() == 0) {
                                    if (backupEventIDStr == null) {
                                        backupEventIDStr = backupEventID + "";
                                    } else {
                                        backupEventIDStr = backupEventIDStr + "," + backupEventID;
                                    }
                                }
                                for (int j = 0; j < backupPhoto.size(); j++) {
                                    ShowBackup.DataBean.BackupPhotoBean backupPhotoBean = backupPhoto.get(j);
                                    String getThumbnail = backupPhotoBean.getThumbnail();
                                    String backupPhotoURL = backupPhotoBean.getBackupPhotoURL();
                                    int backupPhotoID = backupPhotoBean.getBackupPhotoID();
                                    YNNativeImage mNativeItem = new YNNativeImage(getThumbnail, backupPhotoURL, backupDate, backupPhotoID, backupEventID);
                                    mNativeImageList.add(mNativeItem);
                                }
                            }
                            deletedDays(backupEventIDStr);
                            date = data.get(data.size() - 1).getBackupDate();
                            Collections.sort(mNativeImageList, new YNNativeComparator());
                            for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
                                YNNativeImage mNativeItem = it.next();
                                String ym = mNativeItem.getTime();
                                if (!sectionMap.containsKey(ym)) {
                                    mNativeItem.setSection(section);
                                    sectionMap.put(ym, section);
                                    section++;
                                } else {
                                    mNativeItem.setSection(sectionMap.get(ym));
                                }
                            }
                            mAdapter.update(mNativeImageList, isSelected);
                            mAdapter.notifyDataSetChanged();
                            showToast("加载完成啦...");
                        } else {
                            Log.d("yuhao", "UploadToYiNian=" + "fail");
                        }
                        isLoading = false;
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        isLoading = false;
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    List<ShowBackup.DataBean> data;

    // 数据绑定
    private void data2View() {
        String showBackup1 = getIntent().getStringExtra("showBackup");
        if (showBackup1 != null) {
            ShowBackup showBackup = gson.fromJson(showBackup1, ShowBackup.class);
            List<ShowBackup.DataBean> data = showBackup.getData();
            String backupEventIDStr = null;
            for (int i = 0; i < data.size(); i++) {
                String backupDate = data.get(i).getBackupDate();
                int backupEventID = data.get(i).getBackupEventID();
                List<ShowBackup.DataBean.BackupPhotoBean> backupPhoto = data.get(i).getBackupPhoto();
                if (backupPhoto.size() == 0) {
                    if (backupEventIDStr == null) {
                        backupEventIDStr = backupEventID + "";
                    } else {
                        backupEventIDStr = backupEventIDStr + "," + backupEventID;
                    }
                }
                for (int j = 0; j < backupPhoto.size(); j++) {
                    ShowBackup.DataBean.BackupPhotoBean backupPhotoBean = backupPhoto.get(j);
                    String getThumbnail = backupPhotoBean.getThumbnail();
                    String backupPhotoURL = backupPhotoBean.getBackupPhotoURL();
                    int backupPhotoID = backupPhotoBean.getBackupPhotoID();
                    YNNativeImage mNativeItem = new YNNativeImage(getThumbnail, backupPhotoURL, backupDate, backupPhotoID, backupEventID);
                    mNativeImageList.add(mNativeItem);
                }
            }
//            Log.d("yuhao", "backupEventIDStr="+backupEventIDStr);
            deletedDays(backupEventIDStr);
            date = data.get(data.size() - 1).getBackupDate();
            Collections.sort(mNativeImageList, new YNNativeComparator());
            for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
                YNNativeImage mNativeItem = it.next();
                String ym = mNativeItem.getTime();
                if (!sectionMap.containsKey(ym)) {
                    mNativeItem.setSection(section);
                    sectionMap.put(ym, section);
                    section++;
                } else {
                    mNativeItem.setSection(sectionMap.get(ym));
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    // 显示备份照片
    private void showBackup() {
//        mProgressDialog = ProgressDialog.show(this, "", "");
        String urlsto = getString(R.string.BASE_URL) + getString(R.string.showBackupPhotos);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, application.getCurID() + "");
        mParam.put(CommonConstants.SIGN, "initialize");
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        ShowBackup showBackup = gson.fromJson(s, ShowBackup.class);
                        if (TextUtils.equals(showBackup.getMsg(), "success")) {
                            List<ShowBackup.DataBean> data = showBackup.getData();
                            String backupEventIDStr = null;
                            mNativeImageList.clear();
                            for (int i = 0; i < data.size(); i++) {
                                String backupDate = data.get(i).getBackupDate();
                                int backupEventID = data.get(i).getBackupEventID();
                                List<ShowBackup.DataBean.BackupPhotoBean> backupPhoto = data.get(i).getBackupPhoto();
                                if (backupPhoto.size() == 0) {
                                    if (backupEventIDStr == null) {
                                        backupEventIDStr = backupEventID + "";
                                    } else {
                                        backupEventIDStr = backupEventIDStr + "," + backupEventID;
                                    }
                                }
                                for (int j = 0; j < backupPhoto.size(); j++) {
                                    ShowBackup.DataBean.BackupPhotoBean backupPhotoBean = backupPhoto.get(j);
                                    String getThumbnail = backupPhotoBean.getThumbnail();
                                    String backupPhotoURL = backupPhotoBean.getBackupPhotoURL();
                                    int backupPhotoID = backupPhotoBean.getBackupPhotoID();
                                    YNNativeImage mNativeItem = new YNNativeImage(getThumbnail, backupPhotoURL, backupDate, backupPhotoID, backupEventID);
                                    mNativeImageList.add(mNativeItem);
                                }
                            }
                            deletedDays(backupEventIDStr);
                            if (data.size() != 0) {
                                date = data.get(data.size() - 1).getBackupDate();
                            }
                            Collections.sort(mNativeImageList, new YNNativeComparator());
                            for (ListIterator<YNNativeImage> it = mNativeImageList.listIterator(); it.hasNext(); ) {
                                YNNativeImage mNativeItem = it.next();
                                String ym = mNativeItem.getTime();
                                if (!sectionMap.containsKey(ym)) {
                                    mNativeItem.setSection(section);
                                    sectionMap.put(ym, section);
                                    section++;
                                } else {
                                    mNativeItem.setSection(sectionMap.get(ym));
                                }
                            }
                            mAdapter.notifyDataSetChanged();
                        } else {
                            Log.d("yuhao", "UploadToYiNian=" + "fail");
                        }
//                        mProgressDialog.dismiss();
                        for (int i = 0; i < mNativeImageList.size(); i++) {
                            if (sortPic.containsKey(mNativeImageList.get(i).getTime())) {
                                List<YNNativeImage> ynNativeImages = sortPic.get(mNativeImageList.get(i).getTime());
                                ynNativeImages.add(mNativeImageList.get(i));
                                sortPic.put(mNativeImageList.get(i).getTime(), ynNativeImages);
                            } else {
                                List<YNNativeImage> ynNativeImages = new ArrayList<>();
                                ynNativeImages.add(mNativeImageList.get(i));
                                sortPic.put(mNativeImageList.get(i).getTime(), ynNativeImages);
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        mProgressDialog.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    public void ToSetWifiDialog() {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        builder.setCancelable(false);
        final android.support.v7.app.AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否去设置WiFi");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("取消");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("去设置");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                dlg.cancel();

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SelectedImg.selectedNetPic.clear();
        SelectedImg.mSelectedImage.clear();
        unregisterReceiver(uploadImgReceiver);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_dustbin:
                if (SelectedImg.selectedNetPic.size() == 0) {
                    showToast("您还没有选择任何图片...");
                    return;
                }
                String backupPhotoIDStr = null;
                for (int i = 0; i < SelectedImg.selectedNetPic.size(); i++) {
                    int backupPhotoID = SelectedImg.selectedNetPic.get(i).getBackupPhotoID();
                    if (backupPhotoIDStr == null) {
                        backupPhotoIDStr = String.valueOf(backupPhotoID);
                    } else {
                        backupPhotoIDStr = backupPhotoIDStr + "," + backupPhotoID;
                    }
//                    Log.d("yuhao", "backupPhotoIDStr="+SelectedImg.selectedNetPic.get(i).getBackupPhotoID());
                }
                deletedSinglePic(backupPhotoIDStr);
                break;
            case R.id.iv_share_import:
                if (SelectedImg.selectedNetPic.size() == 0) {
                    showToast("您还没有选择任何图片...");
                    return;
                }
                startActivity(new Intent(ImporProgressActivity.this, ImportShareActivitty.class));
                break;
            case R.id.iv_import_download:
                if (SelectedImg.selectedNetPic.size() == 0) {
                    showToast("您还没有选择任何图片...");
                    return;
                }
                Long tsLong = System.currentTimeMillis() / 1000;
                String ts = "yn_" + tsLong.toString() + ".png";
                SnackBarUtils.makeShort(mToolbar, "正在下载...").show();
                for (int i = 0; i < SelectedImg.selectedNetPic.size(); i++) {
                    downPic(SelectedImg.selectedNetPic.get(i).getPath(), ts);
                }
                break;
            case R.id.tv_seceted:
                mAdapter.setSelectStatus(true);
                mAdapter.notifyDataSetChanged();
                tv_cancle.setVisibility(View.VISIBLE);
                ll_import_toolbar.setVisibility(View.VISIBLE);
                fab_publish_status.setVisibility(View.GONE);
                ll_import_toolbar.setAlpha(0.8f);
                isSelected = true;
                break;
            case R.id.tv_cancle:
                SelectedImg.selectedNetPic.clear();
                mAdapter.setSelectStatus(false);
                mAdapter.notifyDataSetChanged();
                tv_cancle.setVisibility(View.GONE);
                ll_import_toolbar.setVisibility(View.GONE);
                fab_publish_status.setVisibility(View.VISIBLE);
                isSelected = false;
                break;
        }
    }

    private void deletedSinglePic(String backupPhotoID) {
        mProgressDialog = ProgressDialog.show(this, "", "");
        String urlsto = getString(R.string.BASE_URL) + getString(R.string.ynDeleteSingleBackupPhoto);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.BackupPhotoID, backupPhotoID);
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        mProgressDialog.dismiss();
                        ShowBackup showBackup = gson.fromJson(s, ShowBackup.class);
                        if (TextUtils.equals(showBackup.getMsg(), "success")) {
                            for (int i = 0; i < SelectedImg.selectedNetPic.size(); i++) {
                                mNativeImageList.remove(SelectedImg.selectedNetPic.get(i));
                                mAdapter.update(mNativeImageList, isSelected);
                                mAdapter.notifyDataSetChanged();
                            }
                            SelectedImg.selectedNetPic.clear();
                            showToast("删除成功...");
                        } else {
                            showToast("删除失败...");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                        mProgressDialog.dismiss();
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void deletedDays(String backupEventID) {
        String urlsto = getString(R.string.BASE_URL) + getString(R.string.ynDeleteSingleDayBackupPhotos);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.BackupEventID, backupEventID);
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {

                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {

                    }
                });
        liteHttp.executeAsync(req);
    }

    private void downPic(String url, String name) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(file.mkdir() || file.isDirectory())) {
            file.mkdirs();
        }
        DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        down.setShowRunningNotification(false);
        down.setVisibleInDownloadsUi(false);
        down.setDestinationInExternalPublicDir("yinian/YiNian/", name);
        manager.enqueue(down);
        Log.d("yuhao", "保存成功！");
    }

    @Override
    protected void onRestart() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!start) {
                    toGetProgress();
                    start = true;
                }
            }
        }, 20);
        super.onRestart();
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
